#include "Stdafx.h"
#include "Direct3DSwapChain9.h"

#include "Direct3DSurface9.h"

using namespace Vortex::Wrapper::Direct3D;

Direct3DSwapChain9::Direct3DSwapChain9(IDirect3DSwapChain9* handle) : _handle(handle) {

}

Direct3DSwapChain9::~Direct3DSwapChain9() {
	_handle->Release();
}

HResult Direct3DSwapChain9::GetBackBuffer(UINT BackBuffer, [Out] Direct3DSurface9^% result) {
	result = nullptr;
	IDirect3DSurface9* pHandle = NULL;

	HResult hr = HResult(_handle->GetBackBuffer(BackBuffer, D3DBACKBUFFER_TYPE_MONO, &pHandle));
	if (hr.IsSuccess) {
		result = gcnew Direct3DSurface9(pHandle);
	}

	return hr;
}

HResult Direct3DSwapChain9::Present(Nullable<System::Drawing::Rectangle> sourceRect, Nullable<System::Drawing::Rectangle> destRect, IntPtr destWindowOverride) {
	RECT source, dest;
	RECT *pSource = NULL, *pDest = NULL;
	if (sourceRect.HasValue) {
		source.left = sourceRect.Value.Left;
		source.top = sourceRect.Value.Top;
		source.right = sourceRect.Value.Right;
		source.bottom = sourceRect.Value.Bottom;
		pSource = &source;
	}

	if (destRect.HasValue) {
		dest.left = destRect.Value.Left;
		dest.top = destRect.Value.Top;
		dest.right = destRect.Value.Right;
		dest.bottom = destRect.Value.Bottom;
		pDest = &dest;
	}

	return HResult(_handle->Present(pSource, pDest, (HWND)destWindowOverride.ToPointer(), NULL, 0));
}